package com.pan.old.tools;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;

public class ConvertEntity {



    public <T,E> T convert(Class<T> targetClass, E entityObject,HashMap<String,String> tePropertyNameMap){
        return null;
    }

    public <T,E> T convert(Class<T> targetClass ,E entityObject){
        T taget;
        try {
            Constructor<T> declaredConstructor = targetClass.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            taget = declaredConstructor.newInstance();
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        HashMap<String,Field> targetMap = Arrays.stream(targetClass.getDeclaredFields())
                .collect(HashMap::new,(map,f)->map.put(f.getName(),f),HashMap::putAll);
        Class<E> entityClass = (Class<E>) entityObject.getClass();
        for (Field ef: entityClass.getDeclaredFields()){
            if (!targetMap.containsKey(ef.getName())) {
                continue;
            }
            Field tf = targetMap.get(ef.getName());
            ef.setAccessible(true);
            tf.setAccessible(true);
            try {
                Object value = ef.get(entityObject);
                tf.set(taget,value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return taget;
    }
}
